package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;

import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;

import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangzhenjun
 * @date 2022/2/23 8:58
 */
@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 社交登录回调方法
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/auth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code,HttpSession httpSession) throws Exception {

        Map<String,String> map = new HashMap<>();
        map.put("client_id","638420074");
        map.put("client_secret","afc945dc6a45c4e947dd83295e6d0af8");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/auth2.0/weibo/success");
        map.put("code",code);
        // 根据code换取token
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String, String>(), map, new HashMap<String, String>());
        // 处理
        if (post.getStatusLine().getStatusCode() == 200) {
            // 获取到了token
            String string = EntityUtils.toString(post.getEntity());
            SocialUser socialUser = JSON.parseObject(string, SocialUser.class);

            // 知道当前那个社交用户
            // 如果第一次进入就注册到我们系统，会员系统绑定到社交账号（登录注册）
            R r = memberFeignService.oanthlogin(socialUser);
            if (r.getCode() == 0) {
                //成功
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {});
                log.info("登录成功 ： {}",data);
                // TODO 默认发的令牌，作用域只是自己的，要解决夸不同的网页域名
                httpSession.setAttribute("loginUser",data);
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }

        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
